package com.chengdu.third.controller.admin;

import com.chengdu.third.pojo.User;
import com.chengdu.third.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

import java.util.List;

/**
 * @author jingbo
 * @create 2021--08--18  21:03
 */

@Controller
@RequestMapping("/admin")
public class UserShowController {

    @Autowired
    private IUserService iUserService;


    //查询所有分类的方法
    @GetMapping("/getUsershow")
    public String getUserShow(@RequestParam(required = false,defaultValue = "1",value = "pagenum")int pagenum, Model model){
        //规定第几页，每页多少个
//        pagenum是统计页数的
        PageHelper.startPage(pagenum, 6);
        List<User> allUser = iUserService.findAll();
        //得到分页结果对象
        PageInfo<User> pageInfo = new PageInfo<>(allUser);
        //根据pageInfo来展示出数据
        model.addAttribute("pageInfo", pageInfo);
        return "admin/Usershow";
    }




    //跳转新增用户的页面，放一个空的User到model中
    @GetMapping("/getUsershow/input")
    public String toAddBlog(Model model){
        model.addAttribute("user", new User());  //返回一个blog对象给前端th:object
        return "admin/Usershow-input";
    }

    @PostMapping("/getUsershow")
    public String addUsershow(User user, HttpSession session, RedirectAttributes attributes){
        User user1 = iUserService.getUserByUsername(user.getUsername());
        if(user1!=null){
            attributes.addFlashAttribute("msg", "不能添加重复的用户");
            return "redirect:/admin/getUsershow/input";
        }else{
            attributes.addFlashAttribute("msg", "添加成功");
            iUserService.adduser(user);
        }
        return "redirect:/admin/getUsershow";
    }


    //    删除Usershow
    @GetMapping("/userdelete/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes){
        iUserService.deleteByid(id);
        attributes.addFlashAttribute("msg", "删除成功");
        return "redirect:/admin/getUsershow";
    }

    //    修改Usershow,转移到修改页面
    @GetMapping("/userupdate/{id}/update")
    public String updateUser(@PathVariable Long id, Model model){
        model.addAttribute("user", iUserService.getUserById(id));
         return "admin/Usershow-update";
    }

    //真正修改提交的页面
    @PostMapping("/quserupdate/{id}")
    public String editTag(@PathVariable Long id, User user, RedirectAttributes attributes){  //修改
        iUserService.updateByid(user.getUsername(),user.getPassword(),user.getPhone(),id);
        attributes.addFlashAttribute("msg", "修改成功");
        return "redirect:/admin/getUsershow";
    }



}
